﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Threading;
using System.Diagnostics;

namespace Axe.Windows.Forms
{
    public partial class CultureCapsNotifier : UserControl
    {

        bool isCapsLock = false;
        bool showCaps = false;

        Color m_CapsModeColor = Color.Yellow;
        Color m_DefaultColor = SystemColors.Info;

        public Color DefaultColor
        {
            get { return m_DefaultColor; }
            set { m_DefaultColor = value; }
        }

        public CultureCapsNotifier()
        {
            InitializeComponent();
            UpdateKeyboardLayout();
        }

        private void UpdateKeyboardLayout()
        {
            // isCapsLock = (((ushort)GetKeyState(VK_CAPITAL)) & 0xffff) != 0;

            //if (!isCapsLock)
            //{
                int locId = GetKeyboardLayout(0);
                locId &= 0xFFFF;

                try
                {
                    CultureInfo info = new CultureInfo(locId);
                    string name = info.ThreeLetterWindowsLanguageName;

                    label1.BackColor = DefaultColor;
                    label1.Text = name;
                }
                catch (Exception exc)
                {
                    Debug.WriteLine(exc.Message);
                    label1.Text = CultureInfo.CurrentCulture.ThreeLetterWindowsLanguageName;
                }
            //}
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            UpdateKeyboardLayout();
        }

        [DllImport("user32.dll")]
        private static extern int GetKeyboardLayout(int idThread);
        [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true,CallingConvention = CallingConvention.Winapi)]
        private static extern short GetKeyState(int keyCode);


        // Selections from platform SDK WinUser.h 

        private const int VK_CAPITAL = 0x14;
        private const int VK_INSERT = 0x2D;
        private const int VK_NUMLOCK = 0x90;
        private const int VK_SCROLL = 0x91;

        private void CapsToggleTimer_Tick(object sender, EventArgs e)
        {
            if (isCapsLock)
            {
                showCaps = !showCaps;

                if (showCaps)
                {
                    label1.Text = "Caps";
                }
                else
                {
                    UpdateKeyboardLayout();
                }
            }
        }
    }
}
